#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import re

QUERY	=	"http://search.sipo.gov.cn/sipo/zljs/hyjs-yx-new.jsp?recid="
error_pattern	= ('数据库中无符合条件的专利记录'.decode('utf8')).encode('gb2312')

def input_var(line):
	return (re.findall('value="[^"]+"',line)[0].split("=")[-1]).replace('"','')

class URLsrch:
	def __init__(self,patent):

		if patent[-2] == '.' and len(patent) == 14:
			self.queryURL	= QUERY+patent	
		
		elif patent.isalnum() and len(patent) == 12:
			self.queryURL	= QUERY+patent	

		elif patent.isalnum() and len(patent) == 13:
			tmp		= patent[:-1]+'.'+patent[-1]
			self.queryURL	= QUERY+tmp

		elif patent[-2] == "." and len(patent) == 10:
			self.queryURL	= QUERY+patent	

		elif patent.isalnum() and len(patent) == 8:
			self.queryURL	= QUERY+patent	

		elif patent.isalnum() and len(patent) == 9:
			tmp		= patent[:-1]+'.'+patent[-1]
			self.queryURL	= QUERY+tmp

		else:
			tmp		= patent[:-1]+'.'+patent[-1]
			self.queryURL	= QUERY+tmp


		self.query_info	= None
		self.info_lst	= dict()
	
	def get_info(self):
		self.query_info	=	urllib.urlopen(self.queryURL)
	
	def search(self):
		self.get_info()
		self.info_lst	= dict()

		for line in self.query_info.readlines():
			if error_pattern in line:
				raise Exception("No such patent!\n")
			if "<input" in line:
				if "recid" in line:
					#self.info_lst["recid"]=(re.findall('value="[^"]+"',line)[0].split("=")[-1]).replace('"','')
					self.info_lst["recid"]			= input_var(line)
				elif "tifpath" in line:
					#self.info_lst["tifpath"]=(re.findall('value="[^"]+"',line)[0].split("=")[-1]).replace('"','')
					self.info_lst["tifpath"]		= input_var(line)
				elif "totalpage" in line:
					#self.info_lst["totalpage"]=(re.findall('value="[^"]+"',line)[0].split("=")[-1]).replace('"','')
					self.info_lst["totalpage"]		= input_var(line)
					

if __name__ == '__main__':
	#For test
	testURL	=	URLsrch("200410043401")
	testURL.search()

	print testURL.info_lst
